const express = require('express');
const puppeteer = require('puppeteer');

const fs = require('fs');
const path = require('path');
const axios = require('axios');
const m3u8Parser = require('m3u8-parser');
const cors = require('cors');
const ffmpeg = require('fluent-ffmpeg');
const ffmpegPath = require('@ffmpeg-installer/ffmpeg').path;


const app = express();
const PORT = 4000;

app.get('/fetch-m3u8', async (req, res) => {
    let browser;
    try {
        const targetUrl = req.query.url;
        const fileName = req.query.fileName;
        const staticDir= req.query.staticDir;

        if (!targetUrl) {
            return res.status(400).json({error: 'Missing URL parameter'});
        }

        browser = await puppeteer.launch({
            headless: true,
            args: ['--no-sandbox', '--disable-setuid-sandbox']
        });
        const page = await browser.newPage();

        const m3u8Urls = [];
        page.on('request', request => {
            const url = request.url();
            if (url.includes('.m3u8')) {
                m3u8Urls.push(url);
            }
        });

        await page.goto(targetUrl, {
            waitUntil: 'networkidle2',
            timeout: 30000
        });

        // 修正后的等待方法
        await new Promise(resolve => setTimeout(resolve, 5000));

        if (m3u8Urls.length > 0) {
            // await downloadM3u8(m3u8Urls,fileName,staticDir)
            res.json({
                success: true,
                m3u8Urls: [...new Set(m3u8Urls)]
            });
        } else {
            res.json({
                success: false,
                message: 'No .m3u8 URLs found in network requests'
            });
        }
    } catch (error) {
        console.error('Error:', error);
        res.status(500).json({
            success: false,
            error: error.message
        });
    } finally {
        if (browser) {
            await browser.close();
        }
    }
});

// 设置ffmpeg路径
ffmpeg.setFfmpegPath(ffmpegPath);

// 中间件
app.use(express.json());
app.use(express.urlencoded({ extended: true }));

// 临时文件夹
const tempDir = path.join(__dirname, 'temp');
if (!fs.existsSync(tempDir)) {
    fs.mkdirSync(tempDir);
}

// 转换路由
app.get('/convert', async (req, res) => {
    try {
        const m3u8Url = req.query.url;

        if (!m3u8Url) {
            return res.status(400).json({ error: 'Missing m3u8Url parameter' });
        }

        // 生成唯一文件名
        const outputFileName = `video-${Date.now()}.mp4`;
        const outputPath = path.join(tempDir, outputFileName);

        // 转换m3u8为mp4
        await new Promise((resolve, reject) => {
            ffmpeg(m3u8Url)
                .outputOptions([
                    '-c copy', // 直接复制流，不重新编码
                    '-movflags frag_keyframe+empty_moov' // 确保mp4可以流式播放
                ])
                .output(outputPath)
                .on('end', () => {
                    console.log('Conversion finished');
                    resolve();
                })
                .on('error', (err) => {
                    console.error('Conversion error:', err);
                    reject(err);
                })
                .run();
        });

        // 设置下载头
        res.download(outputPath, outputFileName, (err) => {
            if (err) {
                console.error('Download error:', err);
            }
            // 下载完成后删除临时文件
            fs.unlink(outputPath, (unlinkErr) => {
                if (unlinkErr) console.error('Error deleting temp file:', unlinkErr);
            });
        });

    } catch (error) {
        console.error('Error:', error);
        res.status(500).json({ error: 'Conversion failed', details: error.message });
    }
});


app.listen(PORT, () => {
    console.log(`Server running on http://localhost:${PORT}`);
});